package com.tjh2.preparedstatement.crud;

import com.tjh2.bean.Customer;
import com.tjh2.bean.Order;
import com.tjh2.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PreparedStatementQueryTest
 * @Description ：使用PreparedStatement实现对于不同表的通用的查询操作
 * @Author tang'jia'hao
 * @Date 2021/9/16 16:32
 * @Version 1.0
 **/
public class PreparedStatementQueryTest {

    @Test
    public void testGetForList(){

        String sql = "select id,name,email from customers where id < ?";
        List<Customer> list = getForList(Customer.class, sql, 12);
        list.forEach(System.out::println);

        String sql1 = "select order_id orderId,order_name orderName from `order` where order_id < ?";
        List<Order> orderList = getForList(Order.class, sql1, 5);
        orderList.forEach(System.out::println);

        String sql2 = "select order_id orderId,order_name orderName from `order`";
        List<Order> orderList2 = getForList(Order.class, sql2);
        orderList2.forEach(System.out::println);

    }

    public <T> List<T> getForList(Class<T> clazz, String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 连接mysql
            conn = JDBCUtils.getConnection();
            // 预编译sql语句
            ps = conn.prepareStatement(sql);
            // 初始化sql语句
            for(int i = 0; i < args.length; i++){
                ps.setObject(i + 1, args[i]);
            }
            // 执行操作
            rs = ps.executeQuery();

            // 获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            // 获取列数
            int columnCount = rsmd.getColumnCount();
            // 创建集合对象
            ArrayList<T> list = new ArrayList<>();
            while(rs.next()){
                T t = clazz.newInstance();
                // 给t对象的指定属性赋值:处理结果集中的每一行数据的每一列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columnValue = rs.getObject(i + 1);
                    // 获取列的别名
                    String columnLabel= rsmd.getColumnLabel(i + 1);
                    // 反射机制
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }

        // 此行出异常的时候执行
        return null;
    }

    @Test
    public void testGetInstance(){
        String sql = "select id,name,email from customers where id = ?";
        Customer customer = getInstance(Customer.class, sql, 12);
        System.out.println("customer = " + customer);

        String sql1 = "select order_id orderId,order_name orderName from `order` where order_id = ?";
        Order order = getInstance(Order.class, sql1, 1);
        System.out.println("order = " + order);
    }

    /**
     * 针对于不同的表的通用的查询操作,返回表中的一条记录
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T getInstance(Class<T> clazz, String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 连接mysql
            conn = JDBCUtils.getConnection();
            // 预编译sql语句
            ps = conn.prepareStatement(sql);
            // 初始化sql语句
            for(int i = 0; i < args.length; i++){
                ps.setObject(i + 1, args[i]);
            }
            // 执行操作
            rs = ps.executeQuery();

            // 获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            // 获取列数
            int columnCount = rsmd.getColumnCount();
            if(rs.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columnValue = rs.getObject(i + 1);
                    // 获取列的别名
                    String columnLabel= rsmd.getColumnLabel(i + 1);
                    // 反射机制
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }

        return null;
    }
}
